const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

var homeData = require("../data/home_data.js");

function getHomeData() {
  return homeData.homeData;
}
function isEmpty(target) {
  if (typeof target == 'undefined' || null == target || target == '') {
    return true;
  }else {
    return false;
  }
}
//微信获得位置
function getUserLocation(callback) {
  wx.getLocation({
    type: 'wgs84',
    success: function (res) {
      // console.log(res);
      var latitude = res.latitude
      var longitude = res.longitude
      var speed = res.speed
      var accuracy = res.accuracy
      callback.success(res);
    }
  })
}
var EARTH_RADIUS = 6378137.0;    //单位M
var PI = Math.PI;
function getRad(d) {
  return d * PI / 180.0;
}
/**
 * caculate the great circle distance
 * @param {Object} lat1
 * @param {Object} lng1
 * @param {Object} lat2
 * @param {Object} lng2
 */

function getGreatCircleDistance(lat1, lng1, lat2, lng2) {
  var radLat1 = getRad(lat1);
  var radLat2 = getRad(lat2);

  var a = radLat1 - radLat2;
  var b = getRad(lng1) - getRad(lng2);

  var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
  s = s * EARTH_RADIUS;
  s = Math.round(s * 10000) / 10000.0;
  return s;
}

/*
    @function     JsonSort 对json排序
    @param        json     用来排序的json
    @param        key      排序的键值
*/
function JsonSort(json, key) {
  //console.log(json);
  for (var j = 1, jl = json.length; j < jl; j++) {
    var temp = json[j],
      val = temp[key],
      i = j - 1;
    while (i >= 0 && json[i][key] > val) {
      json[i + 1] = json[i];
      i = i - 1;
    }
    json[i + 1] = temp;
  }
  //console.log(json);
  return json;
}

function decodeTimePrice(jsonString) {
  if (!jsonString) {
    return null;
  }
  let result = JSON.parse(jsonString);
  return result;
}
// var json = JsonSort(willSort, 'age');
// console.log(json);

function isInCollect(list, target) {
  console.log("util : isInCollect", list, target);
  if (!list || !target) {
    return;
  }
  for (var i = 0; i < list.length; i++) {
    let item = list[i];
    console.log("collects", item);
  }

}

module.exports = {
  formatTime: formatTime
}
module.exports.getHomeData = getHomeData;
module.exports.isEmpty = isEmpty;
module.exports.getUserLocation = getUserLocation;
module.exports.getGreatCircleDistance = getGreatCircleDistance;
module.exports.JsonSort = JsonSort;
module.exports.decodeTimePrice = decodeTimePrice;
module.exports.isInCollect = isInCollect;